import * as Koa from 'koa'
import * as koaBody from 'koa-body'
import * as koastatic from 'koa-static'
import * as path from 'path'

import config from './config'
import router from './router'
import * as db from './db'
import logger from './middlewares/logger'
import { ReqStat } from './stats'
import user from './middlewares/user'
const app = new Koa()

app.use(async (ctx, next) => {
  try {
    const start = Date.now()
    await next()
    const time = Date.now() - start
    ctx.set('X-Response-Time', time + 'ms')
  } catch (error) {
    if (error instanceof ReqStat) {
      ctx.status = error.statusCode || 500
      ctx.body = {
        stat: error.stat,
        msg: error.msg
      }
    } else {
      ctx.status = 500
      ctx.body = error.msg
    }
  }
})
app.use(logger)
app.use(user)
app.use(koastatic(path.join(__dirname, '../public')))

app.use(
  koaBody({
    multipart: true,
    formidable: {
      maxFileSize: 2097152
    }
  })
)
app.use(router.routes())
app.listen(config.port)
db.toConnect()
